#!/usr/bin/env node

const { execSync } = require('child_process');
const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

async function publish() {
  try {
    console.log('🚀 准备发布组件库到npm...');
    
    // 检查是否已登录npm
    try {
      execSync('npm whoami', { stdio: 'pipe' });
    } catch (error) {
      console.log('❌ 请先登录npm: npm login');
      process.exit(1);
    }

    // 检查构建文件是否存在
    if (!fs.existsSync('dist')) {
      console.log('📦 构建文件不存在，开始构建...');
      execSync('node scripts/build.js', { stdio: 'inherit' });
    }

    // 检查package.json中的版本
    const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));
    console.log(`📦 当前版本: ${packageJson.version}`);

    // 询问是否要更新版本
    const answer = await new Promise((resolve) => {
      rl.question('是否要更新版本号？(y/n): ', resolve);
    });

    if (answer.toLowerCase() === 'y') {
      const versionType = await new Promise((resolve) => {
        rl.question('版本类型 (patch/minor/major): ', resolve);
      });
      
      execSync(`npm version ${versionType}`, { stdio: 'inherit' });
    }

    // 发布到npm
    console.log('📤 发布到npm...');
    execSync('npm publish', { stdio: 'inherit' });

    console.log('✅ 发布成功！');
    console.log(`📦 包名: ${packageJson.name}`);
    console.log(`📦 版本: ${packageJson.version}`);
    console.log('🔗 安装命令: npm install ' + packageJson.name);

  } catch (error) {
    console.error('❌ 发布失败:', error.message);
    process.exit(1);
  } finally {
    rl.close();
  }
}

publish();
